<template>
  <div>
    <div>
      <el-row v-show="!showEdit">
        <el-button type="primary" icon="Plus" @click="handleCreate"
          >新增
        </el-button>
      </el-row>
      <el-row v-show="showEdit">
        <el-button type="primary" icon="Back" @click="backTable"
          >返回
        </el-button>
        <el-button type="success" icon="Check" @click="submitForm"
          >保存
        </el-button>
      </el-row>
    </div>
    <el-divider></el-divider>
    <div v-show="!showEdit">
      <el-form :inline="true" @submit.prevent>
        <el-form-item label="表名">
          <el-input
            v-model="query.tableName"
            placeholder="请输入表名"
            @keyup.enter="currentChange(1)"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="currentChange(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div v-show="!showEdit">
      <el-table
        :data="tableData"
        row-key="tableId"
        border
        default-expand-all
        stripe
      >
        <el-table-column prop="tableName" label="表名" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="className" label="类名" show-overflow-tooltip>
        </el-table-column>
        <el-table-column
          prop="tableComment"
          label="表描述"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" icon="Download" @click="genCode(scope.row)"
              >生成</el-button
            >
            <el-button size="small" icon="Edit" @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              icon="Delete"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" class="row-bg" justify="end">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.current"
          :page-size="query.size"
          :total="query.total"
          @current-change="currentChange"
        >
        </el-pagination>
      </el-row>
    </div>

    <div v-show="showEdit">
      <el-tabs type="border-card">
        <el-tab-pane label="基本信息">
          <el-form
            ref="formValidate"
            :model="form"
            :rules="rules"
            label-width="80px"
          >
            <el-row>
              <el-col :span="5">
                <el-form-item label="表名" prop="tableName">
                  <el-input
                    v-model="form.tableName"
                    placeholder="表名（下划线风格）"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="表描述" prop="tableComment">
                  <el-input v-model="form.tableComment"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5">
                <el-form-item label="作者" prop="author">
                  <el-input v-model="form.author" placeholder="作者"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="生成路径" prop="outPath">
                  <el-input v-model="form.outPath"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="包路径" prop="packageName">
                  <el-input v-model="form.packageName"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5">
                <el-button type="primary" @click="addTableLine"
                  >增加字段</el-button
                >
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-table
                    :data="form.tableColumns"
                    row-key="tableColumnId"
                    style="width: 100%"
                  >
                    <el-table-column prop="columnName" label="列名" width="180">
                      <template #default="scope">
                        <el-input
                          prop="columnName"
                          v-model="scope.row.columnName"
                          placeholder="列名"
                        ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="columnType"
                      label="列类型"
                      width="150"
                    >
                      <template #default="scope">
                        <el-select
                          v-model="scope.row.columnType"
                          placeholder="选择类型"
                        >
                          <el-option
                            v-for="item in columnTypeOptions"
                            :key="item.label"
                            :label="item.label"
                            :value="item.label"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="columnLength"
                      label="列长度"
                      width="100"
                    >
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.columnLength"
                          maxlength="5"
                          type="number"
                        ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="decimalLength"
                      label="小数点"
                      width="100"
                    >
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.decimalLength"
                          maxlength="5"
                          type="number"
                        ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="columnComment"
                      label="列描述"
                      width="240"
                    >
                      <template #default="scope">
                        <el-input
                          prop="columnComment"
                          v-model="scope.row.columnComment"
                          placeholder="列描述"
                        ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="primaryKey" label="主键" width="60">
                      <template #default="scope">
                        <el-checkbox
                          v-model="scope.row.primaryKey"
                          size="large"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="autoIncrement"
                      label="自增"
                      width="60"
                    >
                      <template #default="scope">
                        <el-checkbox
                          v-model="scope.row.autoIncrement"
                          size="large"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column prop="nullable" label="空值" width="60">
                      <template #default="scope">
                        <el-checkbox
                          v-model="scope.row.nullable"
                          size="large"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="defaultValue"
                      label="默认值"
                      width="150"
                    >
                      <template #default="scope">
                        <el-input
                          prop="defaultValue"
                          v-model="scope.row.defaultValue"
                          placeholder="默认值"
                        ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column width="150">
                      <template #default="scope">
                        <el-button
                          type="danger"
                          @click="handleDeleteLine(scope.$index)"
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup name="Table">
import {
  pageTable,
  selectTableById,
  addTable,
  updateTable,
  deleteTable,
  generateCode,
} from "@/api/table";
import { ElMessageBox } from "element-plus";
import { ElMessage } from "element-plus";
import { ref, onMounted } from "vue";

let formValidate = ref();
let showEdit = ref(false);
let query = ref({ size: 10, current: 0, total: 1 });
let datetime = ref([]);
let form = ref({ tableColumns: [], mode: "CAMEL_CASE" });
let tableData = ref([]);
let rules = ref({
  tableName: [{ required: true, message: "请输入表名", trigger: "blur" }],
  tableComment: [{ required: true, message: "请输入表描述", trigger: "blur" }],
  author: [{ required: true, message: "请输入作者", trigger: "blur" }],
  outPath: [{ required: true, message: "请输入生成路径", trigger: "blur" }],
  packageName: [{ required: true, message: "请输入包路径", trigger: "blur" }],
});
let columnTypeOptions = ref([
  {
    label: "varchar",
  },
  {
    label: "text",
  },
  {
    label: "tinyint",
  },
  {
    label: "int",
  },
  {
    label: "integer",
  },
  {
    label: "bigint",
  },
  {
    label: "date",
  },
  {
    label: "datetime",
  },
  {
    label: "float",
  },
  {
    label: "double",
  },
  {
    label: "decimal",
  },
]);
function currentChange(current) {
  query.value.current = current;
  query.value.startTime = datetime.value[0];
  query.value.endTime = datetime.value[1];
  loadData();
}
function loadData() {
  pageTable(query.value)
    .then((res) => {
      query.value.size = res.data.size;
      query.value.current = res.data.current;
      query.value.total = res.data.total;
      tableData.value = res.data.records;
    })
    .catch((err) => {
      console.log(err);
    });
}
function resetForm() {
  form.value = {};
}
function backTable() {
  resetForm();
  showEdit.value = false;
}
function addTableLine() {
  form.value.tableColumns.push({ columnLength: 0, decimalLength: 0 });
}
function handleDeleteLine(index) {
  form.value.tableColumns.splice(index, 1);
}
function genCode(row) {
  generateCode(row.tableId)
    .then((res) => {
      ElMessage.success("下载成功");
    })
    .catch((err) => {
      console.log(err);
    });
}
function handleUpdate(row) {
  selectTableById(row.tableId)
    .then((res) => {
      showEdit.value = true;
      form.value = JSON.parse(JSON.stringify(res.data));
    })
    .catch((err) => {
      console.log(err);
    });
}
function handleCreate() {
  showEdit.value = true;
}
function handleDelete(row) {
  ElMessageBox.confirm("此操作将永久删除该记录, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteTable(row.tableId)
        .then((res) => {
          ElMessage.success("删除成功");
          currentChange(1);
        })
        .catch((err) => {
          console.log(err);
        });
    })
    .catch((err) => {
      ElMessage.message({
        type: "info",
        message: "取消删除",
      });
    });
}
function submitForm() {
  formValidate.value.validate((valid) => {
    if (valid) {
      if (form.value.tableId != null) {
        updateTable(form.value)
          .then((res) => {
            showEdit.value = false;
            resetForm();
            ElMessage.success("修改成功");
            loadData();
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        addTable(form.value)
          .then((res) => {
            showEdit.value = false;
            resetForm();
            ElMessage.success("保存成功");
            loadData();
          })
          .catch((err) => {
            console.log(err);
          });
      }
    }
  });
}

onMounted(() => {
  loadData();
});
</script>

<style></style>
